package com.tramp.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.tramp.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tramp.basic.entity.Admin;
import com.tramp.basic.service.AdminService;
import com.tramp.basic.service.MenuService;
import com.tramp.basic.vo.MenuVO;
import com.tramp.frame.server.base.BaseController;
import com.tramp.frame.server.base.ResultData;
import com.tramp.frame.server.exception.GenericException;

/**
 * @author chenjm1
 * @since 2017/11/21
 */
@Controller
@RequestMapping("/login/")
public class LoginController extends BaseController {

	@Autowired
	private MenuService menuService;
	@Autowired
	private AdminService adminService;

	@RequestMapping("page")
	public String loginPage() {

		return "login";
	}

	/**
	 * 登录
	 * @param session
	 * @param username
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("login")
	public ResultData login(HttpSession session, String username, String password) {
		Admin admin = adminService.login(username, MD5Utils.encrypt(password));
		if (admin == null) {
			throw new GenericException("账户或密码错误");
		}
		if (!admin.getStatus()) {
			throw new GenericException("账户已禁用");
		}
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, MD5Utils.encrypt(password));
		Subject subject = SecurityUtils.getSubject();
		subject.login(usernamePasswordToken); //完成登录

		//获取菜单
		if (session.getAttribute("menus") == null) {
			List<MenuVO> menuVOList = menuService.getAuthMenus(admin.getId());
			session.setAttribute("menus", menuVOList);
		}
		return success();
	}

	/**
	 * 退出
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("loginOut")
	public ResultData loginOut(HttpSession session) {
		session.removeAttribute("menus");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return success();
	}
}
